<?php
namespace app\api\controller;

use app\api\common\Program;
use app\api\common\WxPay;
use app\api\common\AppPay;
use app\common\controller\Api;
use app\common\model\User as UserModel;
use app\common\model\Config as ConfigModel;
use app\common\model\ChatGroup as ChatGroupModel;
use app\common\model\ChatRoom as ChatRoomModel;
use app\common\model\ChatGroupContent as ChatGroupContentModel;
use think\Validate;
use think\Db;

class Chat extends Api
{
    protected $noNeedLogin = ['userBinding'];
    protected $noNeedRight = '*';

    /*
     * 创建群聊
     * @path api/chat/addChatGroup
     * */
    public function addChatGroup()
    {
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!$params['type']){
            $this->error("群聊类型不能为空");
        }
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        if(!$params){
            $this->error("非法传参");
        }
        if($user['is_chao_group'] != '1'){
            $this->error("非群管理员，无法创建群聊");
        }
        $data = [
            'name'=>$params["name"], //群聊名称
            'type'=>$params["type"], //群聊类型
            'price'=>$params["price"], //群聊保证金
        ];

        $role = [
            'name' => 'require',
            'type' => 'require',
            'price' => 'require',
        ];

        $msg = [
            'name.require'=>'群聊名称不能为空',
            'type.require'=>'群聊类型不能为空',
            'price.require'=>'群聊保证金不能为空',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        if(isset($params['user_ids']) && !empty($params['user_ids'])){
            $data['user_ids'] = $params['user_ids'];
            if($params['type'] == 2){ // 报价群默认全员禁言
                $data['jin_userids'] = removeValueFromString($params['user_ids'],$user_id);
            }
        }else{
            $data['user_ids'] = '';
        }
        if($params['type'] == '1'){//交易群，买家和卖家
            if($data['user_ids']){
                $re_user_arr = explode(",",$data['user_ids']);
                $re_user_count = count($re_user_arr);
                if($re_user_count > 3){
                    $this->error("交易群只能邀请2个人");
                }
            }
        }
        $deposit_kou = ConfigModel::getConfigValue("deposit_kou");
        if($params["price"] < $deposit_kou){
            $this->error("群聊保证金不能少于后台设置的扣除金额");
        }
        $info = ChatGroupModel::where(["name"=>$params["name"],"is_dissolve"=>'0'])->find();
        if($info){
            $this->error("群聊名称已存在");
        }
        $result = ChatRoomModel::createGroup($params["name"],$user->identification);
        $h_id = $result['data']['data']['groupid'];
        $data['user_id'] = $user_id;
        $data['add_time'] = time();
        $res = ChatGroupModel::create($data);
        $group_id = $res->id;
        if($data['user_ids']){
            $user_name = UserModel::where("user_id","IN",$data['user_ids'])->column("identification");
            $h_user_name = array_filter($user_name);
            if($h_user_name){
                ChatRoomModel::groupAddUser($h_id, $h_user_name);
            }
            $user_arr = explode(",",$data['user_ids']);
            foreach ($user_arr as $value){
                $user_room_data = [];
                $user_room_data['user_id'] = $value;
                $user_room_data['to_id'] = $group_id;
                $user_room_data['group_type'] = 2;
                $user_room_data['group_room'] = $group_id;
                if($value == $user_id){
                    $user_room_data['is_margin'] = 1;
                }else{
                    $user_room_data['is_margin'] = 2;
                }
                $user_room_data['type'] = 1;
                $user_room_data['content'] = '';
                $user_room_data['last_time'] = time();
                $user_room_data['add_time'] = time();
                ChatRoomModel::create($user_room_data);
            }
        }
        if($result){
            if($res){
                //消息中心
                $list = ChatRoomModel::chat_content_info($user_id,$group_id,2);
                $is_margin = ChatRoomModel::where(["group_room"=>$group_id,"is_margin"=>1])->column("user_id");
                $list['is_margin'] = $is_margin;
                $list['type'] = 10;
                $list['user_id_str'] = $data['user_ids'];
                $list['group_room'] = $group_id;
                $list['content'] = '';
                $list['last_time'] = getChatTimeStr(time());
                //聊天内容
                $info = [];
                $info['type'] = 10;
                $info['user_id_str'] = $data['user_ids'];
                $info["group_room"] = $group_id;
                $info['is_margin'] = $is_margin;
                $content = [
                    "list" => $list,
                    "info" => $info,
                ];
                ChatGroupModel::where("id",$group_id)->update(["h_id"=>$h_id]);
                ChatRoomModel::sendToGroup($user->identification,$h_id,$content);
                $this->success("创建成功");
            }else{
                $this->error("创建失败");
            }
        }else{
            $this->error("创建失败",$result);
        }
    }

    /*
     * 查看群聊
     * @path api/chat/chatGroupInfo
     * */
    public function chatGroupInfo()
    {
        $chat_group_id = $this->request->param("chat_group_id");
        if(!$chat_group_id){
            $this->error("群聊id不能为空");
        }
        $info = ChatGroupModel::chat_group_info($chat_group_id);
        $this->success("请求成功",$info);
    }

    /*
     * 全部群成员
     * @path api/chat/groupMembers
     * */
    public function groupMembers()
    {
        $page = $this->request->param("page",1);
        $group_id = $this->request->param("group_id");
        $search = $this->request->param("search");
        if(!$group_id){
            $this->error("群id不能为空");
        }
        $group_info = ChatGroupModel::where("id",$group_id)->find();
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        $list = UserModel::getGroupMembers($page,$search,$group_info->user_ids,$group_info->jin_userids);
        $this->success("请求成功",$list);
    }

    /*
     * 邀请群成员
     * @path api/chat/inviteGroupMembers
     * */
    public function inviteGroupMembers()
    {
        $page = $this->request->param("page",1);
        $group_id = $this->request->param("group_id");
        $search = $this->request->param("search");
        if(!$group_id){
            $this->error("群id不能为空");
        }
        $group_info = ChatGroupModel::where("id",$group_id)->find();
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        $list = UserModel::inviteGroupMembers($page,$search,$group_info->user_ids,$group_info->type);
        $this->success("请求成功",$list);
    }

    /*
     * 加入群聊
     * @path api/chat/joinChatGroup
     * */
    public function joinChatGroup()
    {
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        $chat_group_id = $this->request->param("chat_group_id");
        if(!$chat_group_id){
            $this->error("群聊id不能为空");
        }
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        $info = ChatGroupModel::get($chat_group_id);
        if(!$info){
            $this->error("群聊信息错误");
        }
        $order_no = order_no("L");
        $group_user_data = [];
        $group_user_data["user_id"] = $user_id;
        $group_user_data["group_id"] = $chat_group_id;
        $group_user_data["order_no"] = $order_no;
        $group_user_data["price"] = $info["price"];
        $group_user_data["duan"] = $params["duan"];
        $group_user_data["add_time"] = time();
        $user_name = UserModel::where("user_id",$user_id)->value("identification");
        if(!$user_name){
            $this->error("环信用户信息错误");
        }
        Db::name("chat_group_user")->insert($group_user_data);
        if($params["duan"] == 1){
            $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','群聊保证金');
        }else{
            $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','群聊保证金');
        }
        return json_encode($pay_message);
    }

    /*
     * 退出群聊
     * @path api/chat/quitChatGroup
     * */
    public function quitChatGroup()
    {
        $chat_group_id = $this->request->param("chat_group_id");
        $inquiry_form = Db::name("inquiry_form")->where("group_id",$chat_group_id)->find();
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!$chat_group_id){
            $this->error("群聊ID不能为空");
        }
        $group_info = ChatGroupModel::get($chat_group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        if($group_info['type'] == '1'){
            $this->error("交易群不能主动退出群聊");
        }
        $h_id = $group_info->h_id;
        $content = [
            "list" => ["type"=>12,"user_id"=>$user_id,"group_room"=>$group_info->id],
            "info" => ["type"=>12,"user_id"=>$user_id,"group_room"=>$group_info->id],
        ];
        ChatRoomModel::sendToGroup($user->identification,$group_info->h_id,$content);
        if($group_info["user_ids"]){
            // 将user_ids转换成数组
            $user_ids_array = explode(',', $group_info["user_ids"]);
            // 使用array_search函数查找要删除的值在数组中的位置
            $key = array_search($user_id, $user_ids_array);
            // 如果找到要删除的值，则使用unset函数将其从数组中移除
            if ($key !== false) {
                unset($user_ids_array[$key]);
            }
            // 将过滤后的数组转换回逗号分隔的字符串
            $filtered_user_ids = implode(',', $user_ids_array);
            $group_info->user_ids = $filtered_user_ids;
            $group_info->save();
            $where = "user_id = {$user_id}";
            $where.= " AND group_id = {$chat_group_id}";
            $where.= " AND ispay = '1'";
            $where.= " AND is_tui = 0";
            $chat_user_info = Db::name("chat_group_user")->where($where)->field("price,transaction_id,order_no")->find();
            if($chat_user_info){
                $price = $chat_user_info["price"];
                //是否成交，成交后扣除后台设置的金额
                if($inquiry_form && $inquiry_form['is_bid'] == '2'){
                    $transaction_info = Db::name("inquiry_price")->where(["inquiry_id"=>$inquiry_form["id"],"user_id"=>$user_id,"is_bid"=>'2'])->find();
                }else{
                    $transaction_info = "";
                }
                if($transaction_info){
                    $deposit_kou = ConfigModel::getConfigValue("deposit_kou");
                    $tui_price = bcsub($price,$deposit_kou,2);
                    $kou_price = $deposit_kou;
                    $iskou = 1;
                }else{
                    $tui_price = $price;
                    $kou_price = 0;
                    $iskou = 0;
                }
                $group_user_data = [];
                $group_user_data["tui_price"] = $tui_price;
                $group_user_data["kou_price"] = $kou_price;
                $group_user_data["iskou"] = $iskou;
                $group_user_data["type"] = 1;
                Db::name("chat_group_user")->where($where)->update($group_user_data);
                ChatRoomModel::where(["group_type"=>2,"user_id"=>$user_id,"to_id"=>$chat_group_id])->delete();
                $WxPay = new WxPay();
                if($tui_price != 0){
                    $res = $WxPay->Refund($chat_user_info['transaction_id'], $chat_user_info['order_no'], $tui_price, $price,'退出群聊');
                    if ($res['code'] == 1) {
                        ChatRoomModel::groupDelUser($h_id,[$user->identification]);
                        $this->success("退出成功");
                    }else{
                        $this->error("退出失败",$res);
                    }
                }
            }
        }else{
            $this->error("无群聊成员");
        }
    }

    /*
     * 群聊禁言
     * @path api/chat/prohibitionChatGroup
     * */
    public function prohibitionChatGroup()
    {
        $chat_group_id = $this->request->param("chat_group_id");
        $jin_id_str= $this->request->param("jin_id_str");
        $user = $this->auth->getUser();
        if(!$chat_group_id){
            $this->error("群聊ID不能为空");
        }
        if(!$jin_id_str){
            $this->error("禁言ID不能为空");
        }
        $group_info = ChatGroupModel::get($chat_group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        $content = [
            "list" => ["type"=>7,"jin_user_id"=>$jin_id_str,"group_room"=>$chat_group_id],
            "info" => ["type"=>7,"jin_user_id"=>$jin_id_str,"group_room"=>$chat_group_id],
        ];
        ChatRoomModel::sendToGroup($user->identification,$group_info->h_id,$content);
        if($group_info["jin_userids"]){
            // 将jin_userids和接收到的值都转换成数组
            $jin_userids_array = explode(',', $group_info['jin_userids']);
            $received_values_array = explode(',', $jin_id_str);

            // 使用array_merge函数将两个数组合并
            $merged_userids = array_merge($jin_userids_array, $received_values_array);

            // 使用array_unique函数移除重复的值
            $filtered_userids = array_unique($merged_userids);

            // 将最终的数组转换回逗号分隔的字符串
            $jin_userids = implode(',', $filtered_userids);
            $group_info->jin_userids = $jin_userids;
            $group_info->save();
            $this->success("禁言成功");
        }else{
            $group_info->jin_userids = $jin_id_str;
            $group_info->save();
            $this->success("禁言成功");
        }
    }

    /*
     * 解除禁言
     * @path api/chat/relieveChatGroup
     * */
    public function relieveChatGroup()
    {
        $chat_group_id = $this->request->param("chat_group_id");
        $jin_id_str= $this->request->param("jin_id_str");
        $user = $this->auth->getUser();
        if(!$chat_group_id){
            $this->error("群聊ID不能为空");
        }
        if(!$jin_id_str){
            $this->error("禁言ID不能为空");
        }
        $group_info = ChatGroupModel::get($chat_group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        $content = [
            "list" => ["type"=>8,"jin_user_id"=>$jin_id_str,"group_room"=>$chat_group_id],
            "info" => ["type"=>8,"jin_user_id"=>$jin_id_str,"group_room"=>$chat_group_id],
        ];
        ChatRoomModel::sendToGroup($user->identification,$group_info->h_id,$content);
        if($group_info["jin_userids"]){
            // 将jin_userids和接收到的值都转换成数组
            $jin_userids_array = explode(',', $group_info['jin_userids']);
            $received_values_array = explode(',', $jin_id_str);

            // 使用array_diff函数来过滤user_ids中的值
            $filtered_user_ids = array_diff($jin_userids_array, $received_values_array);

            // 将过滤后的数组转换回逗号分隔的字符串
            $filtered_user_ids_string = implode(',', $filtered_user_ids);
            $group_info->jin_userids = $filtered_user_ids_string;
            $group_info->save();
            $this->success("解除成功");
        }else{
            $this->success("无禁言成员");
        }
    }

    /*
     * 立即邀请
     * @path api/chat/inviteNow
     * */
    public function inviteNow()
    {
        $user = $this->auth->getUser();
        $user_id = $this->auth->user_id;
        $chat_group_id = $this->request->param("chat_group_id");
        $user_id_str= $this->request->param("user_id_str");
        if(!$chat_group_id){
            $this->error("群聊ID不能为空");
        }
        if(!$user_id_str){
            $this->error("邀请人ID不能为空");
        }
        $group_info = ChatGroupModel::get($chat_group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        if($group_info["user_ids"]){
            // 将user_id_str和接收到的值都转换成数组
            $user_ids_array = explode(',', $group_info['user_ids']);
            $received_values_array = explode(',', $user_id_str);
            foreach ($received_values_array as $value){
                $room_info = ChatRoomModel::where(["user_id"=>$value,"to_id"=>$chat_group_id,"group_type"=>2,"information_id"=>'0'])->find();
                if(empty($room_info)){
                    $identification = Db::name("user")->where("user_id",$value)->value("identification");
                    if($identification){
                        ChatRoomModel::groupAddUser($group_info['h_id'],[$identification]);
                    }
                    $user_room_data = [];
                    $user_room_data['user_id'] = $value;
                    $user_room_data['to_id'] = $chat_group_id;
                    $user_room_data['group_type'] = 2;
                    $user_room_data['is_margin'] = 2;
                    $user_room_data['group_room'] = $chat_group_id;
                    $user_room_data['type'] = 1;
                    $user_room_data['number'] = 0;
                    $user_room_data['content'] = '';
                    $user_room_data['last_time'] = time();
                    $user_room_data['add_time'] = time();
                    ChatRoomModel::create($user_room_data);
                }
            }
            // 使用array_merge函数将两个数组合并
            $merged_userids = array_merge($user_ids_array, $received_values_array);

            // 使用array_unique函数移除重复的值
            $filtered_userids = array_unique($merged_userids);

            // 将最终的数组转换回逗号分隔的字符串
            $user_ids = implode(',', $filtered_userids);
            $group_info->user_ids = $user_ids;
            $group_info->save();
            //消息中心
            $room_id = ChatRoomModel::where(["user_id"=>$user_id,"to_id"=>$chat_group_id,"group_type"=>2,"information_id"=>'0'])->value("id");
            $msg_id = ChatGroupContentModel::where("group_id",$chat_group_id)->order("id","desc")->value("id");
            $info = ChatGroupContentModel::get_content_info($msg_id,$room_id);
            $list = ChatRoomModel::chat_content_info($user_id,$chat_group_id,2);
            $is_margin = ChatRoomModel::where(["group_room"=>$chat_group_id,"is_margin"=>1])->column("user_id");
            $list['type'] = 10;
            $list['is_margin'] = $is_margin;
            $list['user_id_str'] = $user_id_str;
            $list['content'] = $info['content'];
            $list['last_time'] = $info['add_time'];
            //聊天内容
            $info['type'] = 10;
            $info['user_id_str'] = $user_id_str;
            $info["group_room"] = $chat_group_id;
            $content = [
                "list" => $list,
                "info" => $info,
            ];
            ChatRoomModel::sendToGroup($user->identification,$group_info->h_id,$content);
            $this->success("邀请成功");
        }else{
            $group_info->user_ids = $user_id_str;
            $group_info->save();
            $this->success("邀请成功");
        }
    }

    /*
     * 群聊邀请
     * @path api/chat/groupInvitation
     * */
    public function groupInvitation()
    {
        $chat_group_id = $this->request->param("chat_group_id");
        if(!$chat_group_id){
            $this->error("群聊ID不能为空");
        }
        $group_info = ChatGroupModel::get($chat_group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        $invite_id = $group_info->user_id;
        $info = ChatRoomModel::invite_info($chat_group_id,$invite_id);
        $this->success("请求成功",$info);
    }

    /*
     * 移除群成员
     * @path api/chat/removeChatGroup
     * */
    public function removeChatGroup()
    {
        $chat_group_id = $this->request->param("chat_group_id");
        $remove_id_str= $this->request->param("remove_id_str");
        $deposit_kou = ConfigModel::getConfigValue("deposit_kou");
        $inquiry_form = Db::name("inquiry_form")->where("group_id",$chat_group_id)->find();
        //$user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!$chat_group_id){
            $this->error("群聊ID不能为空");
        }
        if(!$remove_id_str){
            $this->error("移除ID不能为空");
        }
        $group_info = ChatGroupModel::get($chat_group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        if($group_info["user_ids"]) {
            // 将user_ids和接收到的值都转换成数组
            $user_ids_array = explode(',', $group_info['user_ids']);
            $received_values_array = explode(',', $remove_id_str);
            foreach ($received_values_array as $value){
                if($group_info->user_id == $value){
                    $this->error("不能移除群主自己");
                }
                $where = "user_id = {$value}";
                $where.= " AND group_id = {$chat_group_id}";
                $where.= " AND ispay = '1'";
                $where.= " AND is_tui = 0";
                $chat_user_info = Db::name("chat_group_user")->where($where)->field("price,transaction_id,order_no")->find();
                if($chat_user_info){
                    $price = $chat_user_info["price"];
                    //是否成交，成交后扣除后台设置的金额,报价群
                    if($group_info["type"] == '2'){
                        if($inquiry_form && $inquiry_form['is_bid'] == '2'){
                            $transaction_info = Db::name("inquiry_price")->where(["inquiry_id"=>$inquiry_form["id"],"user_id"=>$value,"is_bid"=>'2'])->find();
                        }else{
                            $transaction_info = "";
                        }
                        if($transaction_info){
                            $tui_price = bcsub($price,$deposit_kou,2);
                            $kou_price = $deposit_kou;
                            $iskou = 1;
                        }else{
                            $tui_price = $price;
                            $kou_price = 0;
                            $iskou = 0;
                        }
                        $group_user_data = [];
                        $group_user_data["tui_price"] = $tui_price;
                        $group_user_data["kou_price"] = $kou_price;
                        $group_user_data["iskou"] = $iskou;
                        $group_user_data["type"] = 2;
                        Db::name("chat_group_user")->where($where)->update($group_user_data);
                        $WxPay = new WxPay();
                        if($tui_price != 0){
                            $res = $WxPay->Refund($chat_user_info['transaction_id'], $chat_user_info['order_no'], $tui_price, $price,'移除群成员');
                            if ($res['code'] != 1) {
                                $this->error("退款失败",$res);
                            }
                        }
                    }else{
                        $group_user_data = [];
                        $group_user_data["tui_price"] = $price;
                        $group_user_data["kou_price"] = 0;
                        $group_user_data["type"] = 2;
                        Db::name("chat_group_user")->where($where)->update($group_user_data);
                        $WxPay = new WxPay();
                        $tui_price = $price;
                        if($tui_price != 0){
                            $res = $WxPay->Refund($chat_user_info['transaction_id'], $chat_user_info['order_no'], $tui_price, $price,'移除群成员');
                            Db::name("test")->where("id",1)->update(["tags"=>"交易群移除群成员","city"=>json_encode($res)]);
                            if ($res['code'] != 1) {
                                $this->error("退款失败",$res);
                            }
                        }
                    }
                }
                $userInfo = UserModel::get($value);
                ChatRoomModel::groupDelUser($group_info->h_id,[$userInfo->identification]);
                //发单条消息
                $content = [
                    "list" => ["type"=>6,"remove_user_id"=>$remove_id_str,"group_id"=>$chat_group_id,"group_room"=>$chat_group_id],
                    "info" => ["type"=>6,"remove_user_id"=>$remove_id_str,"group_id"=>$chat_group_id,"group_room"=>$chat_group_id],
                ];
                ChatRoomModel::sendToUser($user->identification,$userInfo->identification,$content);
            }
            // 使用array_diff函数来过滤user_ids中的值
            $filtered_user_ids = array_diff($user_ids_array, $received_values_array);
            // 将过滤后的数组转换回逗号分隔的字符串
            $filtered_user_ids_string = implode(',', $filtered_user_ids);
            $group_info->user_ids = $filtered_user_ids_string;
            $group_info->save();
        }
        if($group_info["jin_userids"]){
            // 将jin_userids和接收到的值都转换成数组
            $jin_userids_array = explode(',', $group_info['jin_userids']);
            $received_values_array = explode(',', $remove_id_str);
            // 使用array_diff函数来过滤user_ids中的值
            $filtered_user_ids = array_diff($jin_userids_array, $received_values_array);
            // 将过滤后的数组转换回逗号分隔的字符串
            $filtered_user_ids_string = implode(',', $filtered_user_ids);
            $group_info->jin_userids = $filtered_user_ids_string;
            $group_info->save();
        }
        $content = [
            "list" => ["type"=>6,"remove_user_id"=>$remove_id_str,"group_id"=>$chat_group_id,"group_room"=>$chat_group_id],
            "info" => ["type"=>6,"remove_user_id"=>$remove_id_str,"group_id"=>$chat_group_id,"group_room"=>$chat_group_id],
        ];
        ChatRoomModel::sendToGroup($user->identification,$group_info->h_id,$content);
        ChatRoomModel::where(["group_type"=>2,"to_id"=>$chat_group_id])->where("user_id","IN",$remove_id_str)->delete();
        $this->success("移除成功");
    }

    /*
     * 解散群聊
     * @path api/chat/dissolutionChatGroup
     * */
    public function dissolutionChatGroup()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        $chat_group_id = $this->request->param("chat_group_id");
        $is_complete = $this->request->param("is_complete",1);
        $deposit_kou = ConfigModel::getConfigValue("deposit_kou");
        if(!$chat_group_id){
            $this->error("群聊ID不能为空");
        }
        $group_info = ChatGroupModel::get($chat_group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        //$group_identification = UserModel::where("user_id",$group_info['user_id'])->value("identification");
        $inquiry_form = Db::name("inquiry_form")->where("group_id",$chat_group_id)->find();
        if($group_info["user_ids"]){
            // 将user_ids转换成数组
            $user_ids_array = explode(',', $group_info["user_ids"]);
            foreach ($user_ids_array as $v){
//                ChatRoomModel::where(["group_type"=>2,"user_id"=>$v,"to_id"=>$chat_group_id])->update(['delete_time'=>time()]);
                ChatRoomModel::destroy(["group_type"=>2,"user_id"=>$v,"to_id"=>$chat_group_id]);
            }
            //交易群已成交
            if($group_info["type"] == 1 && $is_complete == 2){
                if (($key = array_search($user_id, $user_ids_array)) !== false) {
                    unset($user_ids_array[$key]);
                }
                // 重置索引
                $user_ids_array = array_values($user_ids_array);
                foreach ($user_ids_array as $value){
                    //已成交扣除后台设置的扣除成交人的群聊保证金
                    $where = "user_id = {$value}";
                    $where.= " AND group_id = {$chat_group_id}";
                    $where.= " AND ispay = '1'";
                    $where.= " AND is_tui = 0";
                    $chat_user_info = Db::name("chat_group_user")->where($where)->field("price,transaction_id,order_no")->find();
                    if($chat_user_info){
                        $price = $chat_user_info["price"];
                        $tui_price = bcsub($price,$deposit_kou,2);
                        $group_user_data = [];
                        $group_user_data["is_tui"] = 1;
                        $group_user_data["iskou"] = 1;
                        $group_user_data["tui_price"] = $tui_price;
                        $group_user_data["kou_price"] = $deposit_kou;
                        $group_user_data["type"] = 3;
                        Db::name("chat_group_user")->where($where)->update($group_user_data);
                        $WxPay = new WxPay();
                        if($tui_price != 0){
                            $res = $WxPay->Refund($chat_user_info['transaction_id'], $chat_user_info['order_no'], $tui_price, $price,'解散群聊');
                            if ($res['code'] != 1) {
                                $this->error("退款失败",$res);
                            }
                        }
                    }
                }
            }elseif ($group_info["type"] == 1 && $is_complete == 1){
                if (($key = array_search($user_id, $user_ids_array)) !== false) {
                    unset($user_ids_array[$key]);
                }
                // 重置索引
                $user_ids_array = array_values($user_ids_array);
                foreach ($user_ids_array as $value){
                    //未成交退还群聊保证金
                    $where = "user_id = {$value} AND group_id = {$chat_group_id} AND ispay = '1' AND is_tui = 0";
                    //$where.= " AND group_id = {$chat_group_id}";
                    //$where.= " AND ispay = '1'";
                    //$where.= " AND is_tui = 0";
                    $chat_user_info = Db::name("chat_group_user")->where($where)->field("price,transaction_id,order_no")->find();
                    if($chat_user_info){
                        $tui_price = $chat_user_info["price"];
                        $group_user_data = [];
                        $group_user_data["is_tui"] = 0;
                        $group_user_data["iskou"] = 0;
                        $group_user_data["tui_price"] = $tui_price;
                        $group_user_data["kou_price"] = 0;
                        $group_user_data["type"] = 3;
                        Db::name("chat_group_user")->where($where)->update($group_user_data);
                        $WxPay = new WxPay();
//                        $tui_price = 1;
                        if($tui_price != 0){
                            $res = $WxPay->Refund($chat_user_info['transaction_id'], $chat_user_info['order_no'], $tui_price, $tui_price,'解散群聊');
                            if ($res['code'] != 1) {
                                $this->error("退款失败",$res);
                            }
                        }
                    }
                }
            }else{//报价群逻辑
                foreach ($user_ids_array as $value){
                    // 将过滤后的数组转换回逗号分隔的字符串
                    $filtered_user_ids = implode(',', $user_ids_array);
                    $group_info->user_ids = $filtered_user_ids;
                    $where = "user_id = {$value}";
                    $where.= " AND group_id = {$chat_group_id}";
                    $where.= " AND ispay = '1'";
                    $where.= " AND is_tui = 0";
                    $chat_user_info = Db::name("chat_group_user")->where($where)->field("price,transaction_id,order_no")->find();
                    $price = $chat_user_info["price"];
                    //是否成交，成交后扣除后台设置的金额
                    if($inquiry_form && $inquiry_form['is_bid'] == '2'){
                        $transaction_info = Db::name("inquiry_price")->where(["inquiry_id"=>$inquiry_form["id"],"user_id"=>$value,"is_bid"=>'2'])->find();
                    }else{
                        $transaction_info = "";
                    }
                    if($transaction_info){
                        $tui_price = bcsub($price,$deposit_kou,2);
                        $kou_price = $deposit_kou;
                        $iskou = 1;
                    }else{
                        $tui_price = $price;
                        $kou_price = 0;
                        $iskou = 0;
                    }
                    $group_user_data = [];
                    $group_user_data["tui_price"] = $tui_price;
                    $group_user_data["kou_price"] = $kou_price;
                    $group_user_data["iskou"] = $iskou;
                    $group_user_data["type"] = 3;
                    Db::name("chat_group_user")->where($where)->update($group_user_data);
                    if($chat_user_info){
                        $WxPay = new WxPay();
                        if($tui_price != 0){
                            $res = $WxPay->Refund($chat_user_info['transaction_id'], $chat_user_info['order_no'], $tui_price, $price,'解散群聊');
                            if ($res['code'] != 1) {
                                $this->error("退款失败",$res);
                            }
                        }
                    }
                }
            }
            //环信逻辑
            ChatRoomModel::deleteGroup($group_info->h_id);
            $group_info->is_dissolve = 1;
            $group_info->dissolve_time = time();
            $group_info->save();
            $content = [
                "list" => ["type"=>9,"group_room"=>$chat_group_id],
                "info" => ["type"=>9,"group_room"=>$chat_group_id],
            ];
            $res = ChatRoomModel::sendToGroup($user->identification,$group_info->h_id,$content);
            Db::name("test")->where("id",1)->update(["tags"=>"解散群聊","title"=>json_encode($res)]);
            $this->success("解散成功");
        }else{
            $this->success("解散失败");
        }
    }

    /*
     * 修改群聊名称
     * @ApiMethod (POST)
     * @path api/chat/modifyChatGroup
     * */
    public function modifyChatGroup()
    {
        $user = $this->auth->getUser();
        $chat_group_id = $this->request->param("chat_group_id");
        $name = $this->request->param("name");
        if(!$chat_group_id){
            $this->error("群聊id不能为空");
        }
        $chat_group_info = ChatGroupModel::get($chat_group_id);
        if(!$chat_group_info){
            $this->error("群聊信息错误");
        }
        if(isset($name) && !empty($name)){
            $info = ChatGroupModel::where(["name"=>$name,"is_dissolve"=>'0'])->where("id","<>",$chat_group_id)->find();
            if($info){
                $this->error("群聊名称已存在");
            }
            if($user->open_id){
                $res = Program::TextRecognition($name,$user->open_id);
                if($res['code'] == 200 && $res['label'] != 100){
                    $this->error($res['data']);
                }elseif ($res['code'] == 201) {
                    $this->error($res['data']);
                }
            }
            $chat_group_info->name = $name;
            $content = [
                "list" => ["type"=>11,"group_id"=>$chat_group_id,"name"=>$name,"group_room"=>$chat_group_id],
                "info" => ["type"=>11,"group_id"=>$chat_group_id,"name"=>$name,"group_room"=>$chat_group_id],
            ];
            ChatRoomModel::sendToGroup($user->identification,$chat_group_info->h_id,$content);
        }
        $chat_group_info->save();
        $this->success("修改成功");
    }

    /*
     * 退款调试
     * @ApiMethod (POST)
     * @path api/chat/refund
     * */
    public function refund()
    {
        $transaction_id = "4200002197202406175666808629";
        $order_no = "X20240617174915428664";
        $tui_price = "0.01";
        $WxPay = new WxPay();
        $res = $WxPay->Refund($transaction_id, $order_no, $tui_price, $tui_price,'解散群聊');
        dump($res);die();
    }

    /*
     * 用户设备绑定与解绑
     * @ApiMethod (POST)
     * @path api/chat/userBinding
     * */
    public function userBinding()
    {
        $data = $this->request->param();
        $user_id = $data['identification']?$data['identification']:'';//环信的用户id
        $device_id = $data['device_id']?$data['device_id']:'';//移动端设备标识
        $notifier_name = $data['notifier_name']?$data['notifier_name']:'';//推送证书名称
        $device_token = $data['device_token']?$data['device_token']:'';//推送设备 token
        // 调用解绑与绑定
        $res = ChatRoomModel::binding($user_id, $device_id, $notifier_name, $device_token);
        return $res;
    }


}
